package com.springboot.demo.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.springboot.demo.io.Constants;

/**
 * BIO客户端
 *
 * @author supu
 * @date 2019-12-03 14:38
 **/
public class BIOClient {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            clientRequest(i);
        }
    }

    private static void clientRequest(int i){
        Socket socket = null;
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;
        try {
            socket = new Socket(Constants.HOST, Constants.BIO_PORT);
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printWriter = new PrintWriter(socket.getOutputStream(),true);
            String data = "客户端" + i + "数据";
            // 向服务端发送数据
            printWriter.println(data);
            System.out.println(i + " 客户端请求返回数据 : " + bufferedReader.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(socket != null){
                    socket.close();
                }
                if(bufferedReader != null){
                    bufferedReader.close();
                }
                if(printWriter != null){
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
